package ikelib;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;

/**
 * Extract the WIN Second block. The format of the Second block is like following.
 * offset: value
 * 0-3   : length of this block (include this)
 * 4-9   : BCD Time  year(-2000),month,day,hour,minute,second
 * 10-   : chunks of Channel data
 *  	
 * @author ikechan
 *
 */
public class SecondBlock {
	private ArrayList<ChannelData> ChDataList;
	private wintime	Time;
	private int BlockLength;
	private int fileType = 0; // 0:WinA0 5: WinA5
	
	public SecondBlock(FileInputStream fr, int offset) throws IOException{
		makeBlock(fr,offset);
	}
	public SecondBlock(FileInputStream fr, int offset,int type) throws IOException{
		fileType = type;
		makeBlock(fr,offset);
	}
	public SecondBlock(byte[] c, int offset){
		makeBlock(c,offset);
	}
	
	public SecondBlock(byte[] c, int offset, int type){
		fileType = type;
		makeBlock(c,offset);
	}
	
	private void makeBlock(FileInputStream fr, int offset) throws IOException{
		int max = fr.available();
		if(max<(4+offset)){
			return ;
		}
		byte[] lenbuf = new byte[4];
		fr.read(lenbuf,0,4);
		BlockLength = byteUtil.valueOf4Byte(lenbuf,0);
		if((BlockLength)>max){
			return;
		}
		byte[] c = new byte[BlockLength];
		c[0] = lenbuf[0];
		c[1] = lenbuf[1];
		c[2] = lenbuf[2];
		c[3] = lenbuf[3];
		fr.read(c,4,BlockLength-4);
		makeBlock(c,0);
	}
	private void makeBlock(byte[] c, int offset){
		BlockLength = byteUtil.valueOf4Byte(c,offset);
		offset += 4;
		int len=BlockLength;
		len -= 4;
		
		Time = new wintime(c,offset);
		//System.out.println(Time.fmt());
		offset += Time.length();
		len -= Time.length();
		
		if(fileType==5){
			int ms = (c[offset] & 0xf)*10 + ((c[offset]>>4) & 0xf)*100; 
			Time.setMSec(ms);
			offset ++;
			len --;
			
		}
		
		ChDataList = new ArrayList<ChannelData>();
		int count=0;
		while(len>6){
			ChannelData d = new ChannelData(c,offset,Time,fileType);
			ChDataList.add(d);
			offset += d.length();
			len -= d.length();
			count++;
		}
		//System.out.println(String.format("SecBlkCount=%d",count));
		assert(len==0);
	}	
	
	public int length(){
		return BlockLength;
	}
	public wintime getWinTime(){
		return Time;
	}
	public ArrayList<ChannelData> getChannelDataList(){
		return ChDataList;
	}
}
